package cn.edu.zafu.bigdata.YinMingyan.chapter11;

import java.io.*;
import java.net.*;

// UDP时间客户端
public class UDPTimeClient {
    public static void main(String[] args) {
        //String serverAddress = "127.0.0.1"; // 本机服务器地址
        //int port = 6789; // 服务器端口号

        String serverAddress = "192.168.16.15"; // 连接同学的服务器,同学的局域网IP地址
        int port = 12345; // 同学服务器端口号

        try (DatagramSocket socket = new DatagramSocket()) {
            System.out.println("Sending time request to UDP server at " + serverAddress + ":" + port);

            // 创建请求消息
            String message = "TIME_REQUEST";
            byte[] sendData = message.getBytes();
            InetAddress serverAddressObj = InetAddress.getByName(serverAddress);

            // 发送请求到服务器
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddressObj, port);
            socket.send(sendPacket);

            // 接收服务器响应
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);
            String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("UDP Received time: " + response.trim());

        } catch (UnknownHostException e) {
            System.err.println("Server not found: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("I/O Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}